package jui.view
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	import jui.maps.events.JUIEvent;
	
	import modules.webui.events.WebUIEvent;
	
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	
	import spark.components.Group;
	
	public class MessageInputBase extends Group
	{
		public var textArea: TextArea;
		
		public var toInput: TextInput;
	
		public function MessageInputBase()
		{
			super();
		}
		
		public function getTo(): String
		{
			return toInput.text;
		}
			
		public function getText(): String
		{
			return textArea.text;
		}
			
		public function setText(text: String): void
		{
			textArea.text = text;
			textArea.setSelection( textArea.text.length, textArea.text.length);
		}
		
		public function clearText(): void
		{
			setText('');
		}

		public function setStateFromRoster(jid: String): void
		{
			toInput.text = jid;
			focusInputMessage();
		}
		
		public function setRespondent(jid: String): void
		{
			toInput.text = jid;
			focusInputMessage();
		}
		
		public function focusInputMessage(): void
		{
			textArea.setFocus();
		}
		
		public function setInputMessageText(text: String): void
		{
			setText(text);
			
			focusInputMessage();
		}

		protected function inputMessageKeyUpHandler(event: Event):void 
		{
			var keyEvent: KeyboardEvent = event as KeyboardEvent; 
			var keyEnter: int = Keyboard.ENTER;
			if ( keyEvent && keyEvent.controlKey && keyEvent.keyCode == keyEnter )
			{
				sendMessage();
			}
		}
		
		protected function sendButtonClickHandler(event: Event):void
		{
			sendMessage();
		}
		
		protected function hideReplyPanel():void
		{
			var cancelEvent: WebUIEvent = new WebUIEvent(WebUIEvent.CANCEL_REPLY);
			dispatchEvent(cancelEvent);
		}

		private function sendMessage():void 
		{
			var juiEvent: JUIEvent = new JUIEvent(JUIEvent.JUI_SEND_MESSAGE);
			juiEvent.toJID = toInput.text;
			juiEvent.text = getText();
			
			dispatchEvent(juiEvent);
			clearText();
			
			hideReplyPanel();
		}
	}
}